const uuidv4 = require('uuid/v4');
var crypto = require('crypto');
var fs = require('fs');
var request = require('request');
// var connectJMS = require('../jms/connect.jms');
var fileServerConfig = require('../../app.config/env/fileServer.config');
var adUrl = require('../../app.config/env/adUrl.config');
var constant = require('../common/constant');
var jms = require('../../app.config/env/jms.config');
var Stomp = require('stomp-client');
var queue = jms.merchant_queueName;

var merchantService = require('../service/merchant.service');

module.exports={
    findMerchantByAccount:findMerchantByAccount,
    getStatus:getStatus,
    applyStore:applyStore

}

function findMerchantByAccount(req,res,next){
    var account = req.session.merchant.account;
    var response={};
    merchantService.findMerchantByAccount(account,function (err,doc) {
        if(err){
            console.log("error"+Error(err));
            response.result=false;
            response.code = constant.ServerDown;
            res.json(response);
        }else{
            if(doc){
                response.result=true;
                response.obj=doc;
                req.session.merchant=doc;
                res.json(response);
            }else{
                response.result=false;
                response.code=constant.AccountNoExit;
                res.json(response);
            }
        }
    });
    console.log('end');
}

function getStatus(req,res,next){
    var _id = req.session.merchant._id;
    var url = adUrl.adUrl+adUrl.getStatus;
    request.get({url:url+'/'+_id},function(err,httpResponse,body){
        var response ={};
        var data = JSON.parse(body);
        if(data.result){
            req.session.merchant.status=data.status;
            merchantService.updateMerchant(_id,req.session.merchant,function (err,doc) {
                if(err){
                    console.log("error"+Error(err));
                    response.result=false;
                    response.code = constant.ServerDown;
                    res.json(response);
                }else{
                    response.result = true;
                    response.obj = data.status;
                    if(data.status==constant.Reject){
                        response.errMsg=data.rejectContent;
                    }
                    res.json(response);
                }
            });
        }else{
            response.result=false;
            response.code=constant.ServerDown;
            res.json(response);
        }

    });
}

function applyStore(req,res,next){
    var _id = req.session.merchant._id;
    var newMerchant = req.session.merchant;
    var body = req.body;
    newMerchant.name = body.name;
    newMerchant.address = body.address;
    var files = req.files;
    var imgs=[];
    var response ={};
    if(files.imgCard){
        var cardFileName = files.imgCard.name;
        var idBuf = fs.readFileSync(__dirname+'/../../uploads/'+cardFileName);
        imgs.push({filename: newMerchant.imgCard, file: idBuf.toString('base64')});
        fs.unlink(__dirname+'/../../uploads/'+cardFileName);
    }
    if(files.imgHead){
        var headFileName = files.imgHead.name;
        var headBuf = fs.readFileSync(__dirname+'/../../uploads/'+headFileName);
        imgs.push({filename: newMerchant.imgHead, file: headBuf.toString('base64')});
        fs.unlink(__dirname+'/../../uploads/'+headFileName);
    }

        request.post({url:fileServerConfig.fileServer.url,form:{"files":imgs}},function(err,httpResponse,body){
            if (err) {
                response.result=false;
                response.code = constant.ServerDown;

                res.json(response);
            }else{
                //update db

                merchantService.updateMerchant(_id,newMerchant,function (err,doc) {
                    if(err){
                        console.log("error"+Error(err));
                        response.result=false;
                        response.code = constant.ServerDown;
                        res.json(response);
                    }else{
                        console.log("update success doc:"+doc);
                        response.result=true;
                        response.obj=newMerchant;
                        let protocol = {
                            result:true,
                            data:newMerchant
                        }
                        var connectJMS = new Stomp(jms.host,jms.port,jms.username,jms.password);
                        connectJMS.destination = queue;
                        connectJMS.connect(function () {
                            console.log('protocol1'+JSON.stringify(protocol));
                            connectJMS.publish(connectJMS.destination,JSON.stringify(protocol));
                            connectJMS.disconnect();
                        });
                        res.json(response);
                    }
                });
            }


        });

}